package com.google.code.sprite.generate;

import org.apache.commons.io.FilenameUtils;
import com.google.code.sprite.conf.ColumnConfig;
import com.google.code.sprite.conf.TableConfig;

import java.io.File;
import java.io.StringWriter;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.HTMLWriter;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;

public class ListPageGenerate extends AbstractGenerate {

    public String getSubPackage() {
        return tableConfig.getJavaName().toLowerCase();
    }

    public void writeToFile(TableConfig tableConfig, TableMetaData tableMetaData ) {
        init(tableConfig, tableMetaData);
        String subDir = getWebSubPackagePath();
        String fileName = FilenameUtils.concat(subDir, "list"+entityClass+".ftl");
        String content = generate();
        content = replaceVar(content);
        writeToFile(fileName, content);
    }

    public String generate() {
		List<ColumnConfig> columns=tableConfig.getColumns();
		SAXReader saxReader = new SAXReader();
        File file = getTemplateFile("list-template.xhtml");
		Document document = null;
		if (!file.exists())
			return null;

		try {
			document = saxReader.read(file);
            Element node = (Element)document.selectSingleNode("//form/input[@name='tableName']");
            node = (Element)document.selectSingleNode("//form/input[@name='employeeId']");
            
            node = (Element)document.selectSingleNode("//tr[@id='titleRow']");
            for (ColumnConfig col : columns) {
                if (!col.isListable()) continue;
            	node.addElement("td")
            		.addAttribute("class","tableHeader")
            		.addText(col.getGbname());
            }
            
            node = (Element)document.selectSingleNode("//tr[@id='dataRow']");
            for (ColumnConfig col : columns) {
                if (!col.isListable()) continue;
            	node.addElement("td")
            		.addText("${" + this.entityVar + "."+col.getName()+"?default('')}");
            }

            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setXHTML(false);
            outformat.setExpandEmptyElements(true);

            StringWriter sw=new StringWriter();
            HTMLWriter writer = new HTMLWriter(sw, outformat);
            writer.write(document);
            writer.flush();
            writer.close();
            return sw.toString();

		}catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
    

}
